package com.example.imagepicker.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.example.imagepicker.adapter.PhotoWallAdapter;
import com.example.imagepicker.model.Photo;
import com.example.imagepicker.utils.Utility;
import com.tool.R;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择照片页面 Created by hanj on 14-10-15.
 * 
 * //跳转至最终的选择图片页面
 *   Intent intent = new Intent(MainActivity.this, PhotoWallActivity.class);
 *   intent.putExtra("LastmaxCount", 0);//不传默认最近显示99 传值-1 则为最近显示 所有图片
 *   intent.putExtra("NeedCount", 5);//可以选中图片的位数  传值小于或等于0或不传 视为无限制 
 *   startActivityForResult(intent, requestCode_phone);
 * 
 */
public class PhotoWallActivity extends Activity implements OnClickListener {

    private TextView titleTV;
    private Button confirmBtn;

    private List<Photo> list = new ArrayList<Photo>();//数据源
    private List<String> set = new ArrayList<String>();//保存的选中数据
    private GridView mPhotoWall;
    private PhotoWallAdapter adapter;

    /**
     * 当前文件夹路径
     */
    private String currentFolder = null;
    /**
     * 当前展示的是否为最近照片
     */
    private boolean isLatest = true;
    private int latest_count = 0;//最近的照片数量
    private String latest_first_img;//最近的照片的首张
    private int maxCount = 99;//规定显示最大的最近的照片数量
    private int needCount = -1;//可以选取照片数量
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_wall);
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      
        maxCount = getIntent().getIntExtra("LastmaxCount", 99);//不传默认最近显示99 传值-1 则为最近显示 所有图片
        needCount = getIntent().getIntExtra("NeedCount", -1);//可以选中图片的位数  传值小于或等于0 视为无限制
        if(maxCount<=0){
            maxCount=9999;//算为 所有图片
        }
        
        initTitle();
        initView();

    }

    /**
     * @Description (TODO这里用一句话描述这个方法的作用)
     */
    private void initView() {
        Button phonealbum = (Button) findViewById(R.id.phonealbum);
        phonealbum.setOnClickListener(this);
        Button phonescan = (Button) findViewById(R.id.phonescan);
        phonescan.setOnClickListener(this);
        
        mPhotoWall = (GridView) findViewById(R.id.photo_wall_grid);
        list = getLatestImagePaths(maxCount);
        if(list!=null&&list.size()>0){
            latest_count = list.size();
            latest_first_img = list.get(0).getImgPath();  
        }

        adapter = new PhotoWallAdapter(this, list,set,confirmBtn,needCount);
        mPhotoWall.setAdapter(adapter);

        if(needCount>0){
            confirmBtn.setText("("+set.size()+"/"+needCount+")完成");
        }else{
            confirmBtn.setText("("+set.size()+")完成");  
        }
        
    }

    /**
     * @Description (TODO这里用一句话描述这个方法的作用)
     */
    private void initTitle() {
        titleTV = (TextView) findViewById(R.id.tv_header);
        titleTV.setText("选择照片");

        Button backBtn = (Button) findViewById(R.id.backBtn);
        backBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });

        confirmBtn = (Button) findViewById(R.id.btn_common);//完成
        // 选择照片完成
        confirmBtn.setOnClickListener(this);

    }

    /**
     * 第一次跳转至相册页面时，传递最新照片信息
     */
    private boolean firstIn = true;

    /**
     * 根据图片所属文件夹路径，刷新页面
     */
    private void updateView(int code, String folderPath) {
        list.clear();
        
        if (code == 100) { // 某个相册
            int lastSeparator = folderPath.lastIndexOf(File.separator);
            String folderName = folderPath.substring(lastSeparator + 1);
            titleTV.setText(folderName);
            list.addAll(getAllImagePathsByFolder(folderPath));
        } else if (code == 200) { // 最近照片
            titleTV.setText(R.string.latest_image);
            list.addAll(getLatestImagePaths(maxCount));
        }

        adapter.notifyDataSetChanged();
        if (list.size() > 0) {
            // 滚动至顶部
            mPhotoWall.smoothScrollToPosition(0);
        }
    }

    /**
     * 获取指定路径下的所有图片文件。
     */
    private List<Photo> getAllImagePathsByFolder(String folderPath) {
        File folder = new File(folderPath);
        String[] allFileNames = folder.list();
        if (allFileNames == null || allFileNames.length == 0) {
            return null;
        }

        List<Photo> imageFilePaths = new ArrayList<Photo>();
        for (int i = allFileNames.length - 1; i >= 0; i--) {
            if (Utility.isImage(allFileNames[i])) {
                imageFilePaths.add(new Photo(folderPath + File.separator + allFileNames[i]));
            }
        }

        return imageFilePaths;
    }

    /**
     * 使用ContentProvider读取SD卡最近图片。
     */
    private List<Photo> getLatestImagePaths(int maxCount) {
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String key_MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
        String key_DATA = MediaStore.Images.Media.DATA;

        ContentResolver mContentResolver = getContentResolver();

        // 只查询jpg和png的图片,按最新修改排序
        Cursor cursor = mContentResolver.query(mImageUri, new String[] {key_DATA }, key_MIME_TYPE + "=? or "
                + key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=?",
                new String[] {"image/jpg", "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED);

        if (cursor != null) {
            // 从最新的图片开始读取.
            // 当cursor中没有数据时，cursor.moveToLast()将返回false
            if (cursor.moveToLast()) {

                while (true) {
                    // 获取图片的路径
                    String path = cursor.getString(0);
                    list.add(new Photo(path));

                    if (list.size() >= maxCount || !cursor.moveToPrevious()) {
                        break;
                    }
                }
            }
            cursor.close();
        }

        return list;
    }

    private final static int requestCode_phone = 0x01;
    public final static int requestCode_scan = 0x02;
    /*
     * (非 Javadoc) Description:
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.phonealbum){//相册
            Intent intent = new Intent(this, PhotoAlbumActivity.class);
            // 传递“最近照片”分类信息
            if (latest_count>0) {
                intent.putExtra("latest_count", latest_count);
                intent.putExtra("latest_first_img", latest_first_img);
            }
            startActivityForResult(intent, requestCode_phone);
        }else if(v.getId()==R.id.btn_common){//完成
            // 选择图片完成,回到起始页面
            ArrayList<String> paths = (ArrayList<String>) adapter.getData();
            
            Intent data = new Intent();
            data.putStringArrayListExtra("paths", paths);
            setResult(RESULT_OK, data);
            finish();
        }else if(v.getId()==R.id.phonescan){//预览
            ArrayList<String> paths2 = (ArrayList<String>) adapter.getData();
            List<Photo> photos = new ArrayList<Photo>();
            Photo p=null;
            for(int i=0;i<paths2.size();i++){
                p =new Photo(paths2.get(i));
                p.setStatus(1);
                photos.add(p);
            }
            if(photos.size()>0){
                Intent intent2 = new Intent(this, PhotoScanActivity.class);
                intent2.putExtra("paths", (Serializable)photos);
                intent2.putExtra("NeedCount", needCount);
                startActivityForResult(intent2, requestCode_scan);
            }
            
        }
        
    }
    
    /* (非 Javadoc)
     * Description:
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            switch (requestCode) {
            case requestCode_phone://相册
                int code = data.getIntExtra("code", -1);
                if (code == 100) {
                    // 某个相册
                    String folderPath = data.getStringExtra("folderPath");
                    if (isLatest || (folderPath != null && !folderPath.equals(currentFolder))) {
                        currentFolder = folderPath;
                        updateView(100, currentFolder);
                        isLatest = false;
                    }
                } else if (code == 200) {
                    // “最近照片”
                    if (!isLatest) {
                        updateView(200, null);
                        isLatest = true;
                    }
                }
                break;
            case requestCode_scan://预览  点击完成回来
                ArrayList<String> list = (ArrayList<String>) data.getSerializableExtra("paths");
                setResult(RESULT_OK, new Intent().putStringArrayListExtra("paths", list));
                finish();
                
            default:
                break;
            }
        }
        
    }
}
